package com.sd365.common.core.annotation.mybatis;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.sd365.common.core.common.advice.MyPageInfo;
import com.sd365.common.core.common.pojo.vo.BaseQuery;
import com.sd365.common.core.context.BaseContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @class PaginationAspect
 * @classdesc
 *   <p> abel.zhan 2021-12-07 增加分页常量 </p>
 * @author Administrator
 * @date 2021-1-12  10:56
 * @version 1.0.0
 * @see 
 * @since 
 */
@Aspect
@Slf4j
@Component
public class PaginationAspect {
    /**
     * 优化数字为常量
     */
    private static final int START_PAGE_NUM=1;
    /**
     * 当前系统默认每页20条
     */
    private static final int DEFAULT_PAGE_SIZE=20;
    /**
     * 分页标识 基础框架ControllerAdvise将会取得该值构建统一应答包包含分页信息
     */
    public static final String PAGE_INFO="pageInfo";

    @Pointcut("@annotation(com.sd365.common.core.annotation.mybatis.Pagination)")
    public void pointcut(){
    }

    @Around("pointcut()")
    public Object startPaination(ProceedingJoinPoint joinPoint) throws Throwable {
         execPagination(joinPoint.getArgs());
         Object resultList=joinPoint.proceed();
         if(resultList instanceof  Page){
             Page page=(Page)resultList;
             BaseContextHolder.set("pageInfo", JSON.toJSONString(new MyPageInfo(page.getTotal(), page.getPages())));
         }
         return resultList;
    }


    /**
     * @param: 拦截参数
     * @return:
     * @see
     * @since
     */
    private void execPagination(Object args[]){
        for(Object arg: args){
            if(arg instanceof BaseQuery){
                BaseQuery baseQuery=(BaseQuery)arg;
                //if(BaseContextHolder.get("page")==null){
                    // 开启分页
                if (baseQuery.getPageNum()<=0 || baseQuery.getPageNum()==null){
                baseQuery.setPageNum(START_PAGE_NUM);
                }
                if(baseQuery.getPageSize()<=0){
                baseQuery.setPageSize(DEFAULT_PAGE_SIZE);
                }
                PageMethod.startPage(baseQuery.getPageNum(), baseQuery.getPageSize(), true);
                break;
            }
        }
    }

}
